package metar_taf;

import java.io.IOException;
import java.util.Comparator;
import java.util.PriorityQueue;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class QueryNearestAirportServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		String q = req.getParameter("q");
		String count = req.getParameter("count");
		Airport[] airports = AirportList.createList();
		int cnt;
		if (q == null)
			return;
		if (count == null) {
			cnt = 1;
		} else {
			try {
				cnt = Integer.parseInt(count);
				if (cnt < 1) {
					cnt = 1;
				}
				if (cnt > airports.length) {
					cnt = airports.length;
				}
			} catch (NumberFormatException e) {
				cnt = 1;
			}
		}
		int idx = q.indexOf(",");
		double latitude;
		double longitude;
		try {
			latitude = Double.parseDouble(q.substring(0, idx));
			longitude = Double.parseDouble(q.substring(idx + 1));
		} catch (NumberFormatException e) {
			return;
		}
		Location currentLocation = new Location(latitude, longitude);

		PriorityQueue<Airport> queue = new PriorityQueue<Airport>(
				airports.length, new Comparator<Airport>() {
					@Override
					public int compare(Airport o1, Airport o2) {
						return (int) (o1.distance - o2.distance);
					}
				});
		for (Airport v : airports) {
			v.distance = currentLocation.geoDistance(v.getLocation());
			queue.add(v);
		}
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println("[");
		for (int i = 0; i < cnt; i++) {
			resp.getWriter().print(queue.poll().toJSON());
			if (i != cnt - 1) {
				resp.getWriter().println(",");
			}
		}
		resp.getWriter().println("]");
		resp.flushBuffer();
	}
}
